package com.qing.write

import java.util
import java.util.regex.Pattern

import org.apache.lucene.document.{Document, Field, FieldType, TextField}

/**
  * Created by wuliao on 2017/8/21.
  */
class SimpleParse extends Parse2Document {
  override def parseStrIntoDoc(s: String, doc: Document): Unit = {
    val pattern = "messages[\\s\\S]*:(\\w{3} \\d{2} \\d{2}:\\d{2}:\\d{2})[\\s\\S]+?( nanny\\[[0-9]+\\]: )([\\s\\S]+?(\\d+.\\d+.\\d+.\\d+:\\d+)[\\s\\S]+)"

    val r = Pattern.compile(pattern)
    val m = r.matcher(s)
    if (m.find) {
      val date = m.group(1)
      val reason = m.group(3)
      val ipAndPort = m.group(4)
      val month = getMonth(date.substring(0, 3)) + 1

      val day = date.substring(4, 6)
      val time = date.substring(7).replaceAll(":", "")
      var monthStr = ""
      if (month < 9) {
        monthStr = "0" + month
      } else {
        monthStr = month + ""
      }
      val c = "2017" + monthStr + day + time
      val ip = ipAndPort.split(":")(0)
      val port = ipAndPort.split(":")(1)

      doc.add(new Field("time", c, TextField.TYPE_NOT_STORED))
      doc.add(new Field("ip", ip, TextField.TYPE_NOT_STORED))
      doc.add(new Field("port", port, TextField.TYPE_NOT_STORED))
      doc.add(new Field("reason", reason, TextField.TYPE_NOT_STORED))
    } else {
      println(s)
    }


  }


  def getMonth(s: String): Int = {
    val months = Array[String]("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
    val size = months.length
    for (i <- 0 until size) {
      if (months.apply(i).equals(s)) {
        return i
      }
    }
    0
  }
}
